'use strict';
import React, {

  Component,
  StyleSheet,
  ToastAndroid,
  Text,
  View,
  Image,
  ListView,
  TouchableOpacity,
  ToolbarAndroid,
  TextInput,
  Dimensions
} from 'react-native';

import Register from './Register';
import Storage from 'react-native-storage';
var DialogAndroid = require('react-native-dialogs');
import Loader from '../component/loader/Loader';


import { connect } from 'react-redux';
import {bindActionCreators} from 'redux'

import LoginActions from '../actions/loginAction'
import firstpage from '../Device/firstpage';

 var width = Dimensions.get('window').width; //full width
 var height =Dimensions.get('window').height;
 var loadwidth = width/2;

 let _navigator = null;

 var toolbarActions =[


  {title: '注册', show: 'always'},


];










import getStorage from './storage';

var storage = getStorage().getInstance();

 export default class Login extends Component{


     constructor(props) {
        super(props);

       this.state ={
       	 email:'tw.feng@haihangyun.com',
       	 password:'111111',
         isloging:false
       }




   }

 componentDidMount() {

        _navigator =   this.props.navigator;
 }


	    render(){

	    	return(


          <View style={styles.main}>
	    		<ToolbarAndroid

                       title = {'登陆'}
                       actions={toolbarActions}
                       style={styles.toolbar}

                        onActionSelected={this.onActionSelected.bind(this)}
                       >


                       </ToolbarAndroid>

                <View style={styles.middle}>
                    <View style={styles.email} >
                       <Text  style={{fontSize:18,marginTop:12,height:25,marginLeft:12}}>
                        邮箱
                       </Text>

                       <TextInput
                               keyboardType ='email-address'
                               style={{marginLeft:18,height:50,width:230,fontSize:18}}
                               autoFocus ={true}
                               value={this.state.email}
                               onChangeText={this.oneEmailText.bind(this)}
                             />
                    </View>
                  {  this.props.isLoading && <View style={{left:loadwidth-33,position:'absolute'}}>
                        <Loader
                           size={37}
                           isVisible ={true}
                             type={'ThreeBounce'}
                           color={'#6d9eeb'}

                           />
                    </View>
                   }

                    <View style={styles.password}>
                        <Text  style={{fontSize:18,marginTop:12,height:25,marginLeft:12}}>
                        密码
                       </Text>

                       <TextInput

                               style={{marginLeft:18,height:50,width:230,fontSize:18}}
                              secureTextEntry = {true}
                               value={this.state.password}
                               onChangeText={this.onPassWordText.bind(this)}
                             />
                    </View>
                    <TouchableOpacity onPress={()=>this.login()}>
                        <View style={styles.loginbutton}>
                              <Text style={styles.buttonText}>登陆</Text>
                        </View>
                    </TouchableOpacity >

                    <View style={styles.forget}>
                        <Text>忘记密码</Text>
                    </View>
                </View>


                <View style={styles.bottom}>
		                 <View  style={styles.space}>

		                 </View>
		                 <View  style={styles.qqorchat} >
                            <Image
                              style={{height:60,width:60}}
                              source={require('./image/btn_qq_login.png')} />
                            <Image
                              style={{height:60,width:60,marginLeft:60}}
                              source={require('./image/btn_weixin_login.png')} />
		                 </View>

                 </View>

          </View>


                       )


	    }


	    // onIconClicked(){
	    // 	// alert("如果第一次进入 就推出应用 否则就返回上一个页面")
      //   this.props.navigator.pop()
	    // }
	    onActionSelected(){
	    	this.props.navigator.push({name:"register",
                                    component:Register,
                                    params:{
                                      navigator:this.props.navigator
                                    }})
	    }

	    oneEmailText(text){

		    this.setState({
		        email:text ,
		    });

    }
      onPassWordText(text){

        this.setState({
            password:text ,
        });

    }
     callback(){
        // this.props.navigator.pop();
        _navigator.replace({
          name: 'firstpage',
          component: firstpage});
     }

     saveTickket(ticket){
    //   alert(ticket);
         storage.save({
            key: 'ticket',
            rawData: {
                 Ticket: ticket
   },

         });
     }
      login(){


        // this.setState({
        //   isloging:true
        // });
        // this.callback()
       const {LoginActions} = this.props;
       LoginActions.login(this.state.email,this.state.password,this.callback,this.saveTickket);

        // fetch('http://42.159.150.5:8080/api/v1/users/login',{
        //    method: 'POST',
        //    headers: {
        //       'Content-Type': 'application/json',
        //     },
        //    body: JSON.stringify({
        //         "email":this.state.email,
        //         "password":this.state.password
        //       })
        //
        //   }).then((response) => response.headers.get('token'))
        //       .then((responseText) => {
        //         if (responseText ===null) {
        //                 this.setState({
        //                   isloging:false
        //                 });
        //             var dialog = new DialogAndroid();
        //             dialog.set({
        //
        //                   content: '账号或密码错误',
        //
        //                   negativeText: 'Cancel'
        //                 });
        //             dialog.show();
        //
        //         }
        //           else{
        //
        //
        //                global.storage.save({
        //             key: 'token',  //注意:请不要在key中使用_下划线符号!
        //             rawData: {
        //               token:responseText
        //             },
        //
        //             //如果不指定过期时间，则会使用defaultExpires参数
        //             //如果设为null，则永不过期
        //             expires: null
        //           });
        //
        //           this.props.navigator.pop();
        //
        //           }
        //       })
        //       .catch((error) => {
        //
        //           this.setState({
        //                   isloging:false
        //                 });
        //         var dialog = new DialogAndroid();
        //             dialog.set({
        //
        //                   content: '请打开wifi或移动网',
        //
        //                   negativeText: 'Cancel'
        //                 });
        //             dialog.show();
        //
        //       });
          }

}

const styles = StyleSheet.create({
  toolbar: {
    backgroundColor: '#6d9eeb',
    height: 56,
  },
  main:{
  	flex:1,
  	flexDirection:'column'
  },
  middle:{
  	 alignItems: 'center',

  	flexDirection:'column',
  	height:230,
  	marginTop:100
  },

  email:{
  	flex:1,

  	flexDirection:'row',
  },
  password:{
  	flex:1,

  	flexDirection:'row',

  },
  loginbutton:{
  	borderRadius:5,
  	height:42,
  	width:280,
  	backgroundColor:'#32B16C',
  	 marginLeft:10,
  	 marginTop:16,
  	 alignItems: 'center',
  	 justifyContent: 'center',

  },
  buttonText:{

    color:'#ffffff',
    fontSize:18
  },
  forget:{
  	 marginTop:25
  },
  bottom:{
    flex:1,

  	flexDirection:'column',
  	marginTop:70
  },
  space:{
       height:1,
       backgroundColor:'#41B777',
       marginLeft:15,
       marginRight:15
  },
  qqorchat:{
      marginTop:30,
      justifyContent:'center',
      flexDirection:'row'
  }

  });


export default connect(state=>{  return {isLoading:state.Login.isLoading,isSuccess:state.Login.isSuccess }} ,
  dispatch => {
  return {
    LoginActions: bindActionCreators(LoginActions, dispatch),
     }}
)(Login)
